//
//  RKPaintedGiftView.m
//  WuyouTang
//
//  Created by YB007 on 2020/8/27.
//  Copyright © 2020 cat. All rights reserved.
//

#import "RKPaintedGiftView.h"
#import "RKPaintedHeader.h"

@interface RKPaintedGiftView()
{
    CGPoint _lastPoint;
}
@property(nonatomic,strong)UIView *funBgView;
@property(nonatomic,strong)UIButton *closeBtn;
@property(nonatomic,strong)UIButton *clearLastBtn;
@property(nonatomic,strong)UIButton *clearAllBtn;
@property(nonatomic,strong)UILabel *paintedNumL;            //涂鸦个数
@property(nonatomic,strong)UIView *paintedDesView;          //涂鸦只是说明

@property(nonatomic,strong)NSMutableArray<NSDictionary *> *pointsArray;
@property(nonatomic,strong)NSMutableArray<UIImageView *> *paintedGiftsArray;

@property(nonatomic,assign)CGFloat giftWidth;
@property(nonatomic,assign)CGFloat giftHeight;


@end

@implementation RKPaintedGiftView


- (instancetype)init {
    self = [super init];
    if (self) {
        [self createUI];
    }
    return self;
}

-(void)createUI {
    
    self.backgroundColor = RGB_COLOR(@"#000000", 0.2);
    
    self.pointsArray = [NSMutableArray array];
    self.paintedGiftsArray = [NSMutableArray array];
    
    _giftWidth = _giftHeight = _window_width/10;
    
    [self addSubview:self.paintedDesView];
    [_paintedDesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.mas_width).multipliedBy(0.8);
        make.height.equalTo(self.mas_width);
        make.centerX.equalTo(self);
        make.centerY.equalTo(self.mas_centerY).multipliedBy(0.9);
    }];
    
    [self addSubview:self.funBgView];
    [_funBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).offset(0);
        make.height.mas_equalTo(43);
        make.bottom.equalTo(self.mas_bottom).offset(-1);
        make.left.equalTo(self.mas_left).offset(0);
    }];
   
    UIView *funShadow = [[UIView alloc]init];
    funShadow.backgroundColor = self.backgroundColor;
    [_funBgView addSubview:funShadow];
    [funShadow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerX.centerY.equalTo(_funBgView);
    }];
    
    [_funBgView addSubview:self.paintedNumL];
    
    [_funBgView addSubview:self.closeBtn];
    _funBgView.backgroundColor = RGB_COLOR(@"#ffffff", 1);
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_funBgView.mas_right).offset(-10);
        make.centerY.equalTo(_funBgView);
        make.width.height.mas_equalTo(40);
    }];
    [_funBgView addSubview:self.clearAllBtn];
    [_clearAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.equalTo(_closeBtn);
        make.right.equalTo(_closeBtn.mas_left).offset(-8);
    }];
    [_funBgView addSubview:self.clearLastBtn];
    [_clearLastBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.equalTo(_closeBtn);
        make.right.equalTo(_clearAllBtn.mas_left).offset(-8);
    }];
    
    //默认隐藏
    self.hidden = YES;
    
    [self judgeShowDesView];
    
}
- (void)layoutSubviews {
    [super layoutSubviews];
    [_funBgView layoutIfNeeded];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_funBgView.bounds  byRoundingCorners:UIRectCornerTopRight|UIRectCornerTopLeft cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = _funBgView.bounds;
    maskLayer.path = maskPath.CGPath;
    _funBgView.layer.mask = maskLayer;
}

- (void)setShowPainted:(BOOL)showPainted {
    _showPainted = showPainted;
    
    [_pointsArray removeAllObjects];
    
    self.hidden = !_showPainted;
    
    for (UIImageView* subImgView in _paintedGiftsArray) {
        if ([subImgView isKindOfClass:[UIImageView class]]) {
            [subImgView removeFromSuperview];
        }
    }
    
    //展开时重新布局个数提示
    if (_showPainted) {
        [self judgeShowDesView];
        [_paintedNumL mas_remakeConstraints:^(MASConstraintMaker *make) {
            if (_painteLeftMas) {
                make.left.equalTo(_painteLeftMas).offset(8);
            }else {
                make.left.equalTo(_funBgView).offset(10);
            }
            make.centerY.equalTo(_funBgView);
        }];
    }
    
}
- (CGSize)getPaintedRegion {
    return CGSizeMake(self.width, self.height);
}
-(NSArray<NSString *> *)getPaintedPointArray; {
    
    return [NSArray arrayWithArray:_pointsArray];
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer* )gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer* )otherGestureRecognizer {
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch* >* )touches withEvent:(UIEvent* )event {
    UITouch* touch = [touches anyObject];
    CGPoint point = [touch  locationInView:self];
    //NSLog(@"touchesBegan:x:=%f y:=%f",point.x,point.y);
    
    if ([PublicObj checkNull:_giftPathStr] || CGRectContainsPoint(_funBgView.frame,point)) {
        return;
    }

    if ( point.y > _giftHeight/2 && point.y < self.height-_giftHeight/2 ) {
        
        if (_pointsArray.count < PaintedMaxNum) {
            UIImageView* imageView = [[UIImageView alloc] init];
            [imageView sd_setImageWithURL:[NSURL URLWithString:_giftPathStr]];
            [self addSubview:imageView];
            [_paintedGiftsArray addObject:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker* make) {
                make.top.equalTo(self).offset(point.y - _giftHeight/2);
                make.left.equalTo(self).offset(point.x - _giftWidth/2);
                make.width.mas_equalTo(_giftWidth);
                make.height.mas_equalTo(_giftHeight);
            }];
            
            NSString* x = [NSString stringWithFormat:@"%d",(int)point.x];
            NSString* y = [NSString stringWithFormat:@"%d",(int)point.y];
            
            NSDictionary* pointDic = [NSDictionary dictionaryWithObjectsAndKeys:x,@"x",y,@"y", nil];
            
            //NSString* dicStr = [self dictionaryToJson:pointDic];
            [_pointsArray addObject:pointDic];
            
            _lastPoint = point;
        }
    }
    [self judgeShowDesView];
}

- (void)touchesMoved:(NSSet<UITouch* >* )touches withEvent:(UIEvent* )event {
    UITouch* touch = [touches anyObject];
    CGPoint point = [touch  locationInView:self];
    //NSLog(@"touchesMoved:x:=%f y:=%f",point.x,point.y);
    if ([PublicObj checkNull:_giftPathStr] || CGRectContainsPoint(_funBgView.frame,point)) {
        return;
    }
    if (point.y > _giftHeight/2 && point.y < self.height-_giftHeight/2  ) {
        if ( fabs(point.x - _lastPoint.x) > _giftHeight/2 || fabs(point.y - _lastPoint.y) > _giftHeight/2) {
            if (_pointsArray.count < PaintedMaxNum) {
                UIImageView* imageView = [[UIImageView alloc] init];
                [imageView sd_setImageWithURL:[NSURL URLWithString:_giftPathStr]];
                [self addSubview:imageView];
                [_paintedGiftsArray addObject:imageView];
                [imageView mas_makeConstraints:^(MASConstraintMaker* make) {
                    make.top.equalTo(self).offset(point.y - _giftHeight/2);
                    make.left.equalTo(self).offset(point.x - _giftWidth/2);
                    make.width.mas_equalTo(_giftWidth);
                    make.height.mas_equalTo(_giftHeight);
                }];

                NSString* x = [NSString stringWithFormat:@"%d",(int)point.x];
                NSString* y = [NSString stringWithFormat:@"%d",(int)point.y];
                
                NSDictionary* pointDic = [NSDictionary dictionaryWithObjectsAndKeys:x,@"x",y,@"y", nil];
                
                //NSString* dicStr = [self dictionaryToJson:pointDic];
                [_pointsArray addObject:pointDic];
                
                _lastPoint = point;
            }
        }
    }
    [self judgeShowDesView];
}
-(void)judgeShowDesView {
    if (_pointsArray.count>0) {
        _paintedDesView.hidden = YES;
    }else {
        _paintedDesView.hidden = NO;
    }
    NSString *preStr = YZMsg(@"涂鸦");
    
    NSString *numStr = [NSString stringWithFormat:@" %lu ",(unsigned long)_pointsArray.count];
    NSMutableAttributedString *p_muta = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%@%@",preStr,numStr,YZMsg(@"个")]];
    [p_muta addAttributes:@{NSForegroundColorAttributeName:Pink_Cor} range:NSMakeRange(preStr.length, numStr.length)];
    _paintedNumL.attributedText = p_muta;
}
- (void)touchesEnded:(NSSet<UITouch* >* )touches withEvent:(UIEvent* )event {
    UITouch* touch = [touches anyObject];
    CGPoint point = [touch  locationInView:self];
    NSLog(@"touchesEnded:x:=%f y:=%f",point.x,point.y);
}

- (UIView *)funBgView {
    if (!_funBgView) {
        _funBgView = [[UIView alloc]init];
        _funBgView.backgroundColor = UIColor.clearColor;
    }
    return _funBgView;
}
- (UILabel *)paintedNumL {
    if (!_paintedNumL) {
        _paintedNumL = [[UILabel alloc]init];
        _paintedNumL.font = SYS_Font(12);
        _paintedNumL.textColor = RGB_COLOR(@"#323232", 1);
    }
    return _paintedNumL;
}
- (UIButton *)closeBtn {
    if (!_closeBtn) {
        
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _closeBtn.titleLabel.font = SYS_Font(13);
        [_closeBtn addTarget:self action:@selector(clikcCloseBtn) forControlEvents:UIControlEventTouchUpInside];
        //[_closeBtn setTitle:YZMsg(@"关闭") forState:0];
        //[_closeBtn setTitleColor:Pink_Cor forState:0];
        //_closeBtn.contentEdgeInsets = UIEdgeInsetsMake(5, 8, 5, 8);
        [_closeBtn setImage:[UIImage imageNamed:@"手绘-关闭"] forState:0];
        
        _closeBtn.backgroundColor = UIColor.clearColor;
    }
    return _closeBtn;
}
-(void)clikcCloseBtn {
    self.showPainted = NO;
    if (self.paintedEvent) {
        self.paintedEvent();
    }
}

- (UIButton *)clearAllBtn {
    if (!_clearAllBtn) {
        _clearAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _clearAllBtn.titleLabel.font = SYS_Font(13);
        [_clearAllBtn addTarget:self action:@selector(clikcClearAllBtn) forControlEvents:UIControlEventTouchUpInside];
        //[_clearAllBtn setTitle:YZMsg(@"清除全部") forState:0];
        //[_clearAllBtn setTitleColor:Pink_Cor forState:0];
        //_clearAllBtn.contentEdgeInsets = UIEdgeInsetsMake(5, 8, 5, 8);
        [_clearAllBtn setImage:[UIImage imageNamed:@"手绘-删除"] forState:0];
        
        _clearAllBtn.backgroundColor = UIColor.clearColor;
    }
    return _clearAllBtn;
}
-(void)clikcClearAllBtn {
    
    [_pointsArray removeAllObjects];
    for (UIImageView* subImgView in _paintedGiftsArray) {
        if ([subImgView isKindOfClass:[UIImageView class]]) {
            [subImgView removeFromSuperview];
        }
    }
    [self judgeShowDesView];
}

- (UIButton *)clearLastBtn {
    if (!_clearLastBtn) {
        _clearLastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _clearLastBtn.titleLabel.font = SYS_Font(13);
        [_clearLastBtn addTarget:self action:@selector(clikcClearLastBtn) forControlEvents:UIControlEventTouchUpInside];
        //[_clearLastBtn setTitle:YZMsg(@"回退") forState:0];
        //[_clearLastBtn setTitleColor:Pink_Cor forState:0];
        //_clearLastBtn.contentEdgeInsets = UIEdgeInsetsMake(5, 8, 5, 8);
        [_clearLastBtn setImage:[UIImage imageNamed:@"手绘-回退"] forState:0];
        
        _clearLastBtn.backgroundColor = UIColor.clearColor;
    }
    return _clearLastBtn;
}
-(void)clikcClearLastBtn {
    
    if (_pointsArray.count>0) {
        [_pointsArray removeLastObject];
        UIImageView *imgIV = [_paintedGiftsArray lastObject];
        [imgIV removeFromSuperview];
        [_paintedGiftsArray removeLastObject];
    }
    [self judgeShowDesView];
}

- (UIView *)paintedDesView {
    if (!_paintedDesView) {
        _paintedDesView = [[UIView alloc]init];
        _paintedDesView.backgroundColor = UIColor.clearColor;
        
        UIImageView *desIV = [[UIImageView alloc]init];
        desIV.userInteractionEnabled = YES;
        desIV.image = [UIImage imageNamed:@"手绘-指示"];
        [_paintedDesView addSubview:desIV];
        [desIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(_paintedDesView.mas_width).multipliedBy(0.3);
            make.height.equalTo(desIV.mas_width);
            make.centerY.equalTo(_paintedDesView);
            make.centerX.equalTo(_paintedDesView);
        }];
        UILabel *desL = [[UILabel alloc]init];
        desL.font = SYS_Font(12);
        desL.text = YZMsg(@"绘制礼物,进入涂鸦模式");
        desL.textColor = [UIColor whiteColor];
        [_paintedDesView addSubview:desL];
        [desL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(desIV);
            make.top.equalTo(desIV.mas_bottom).offset(3);
        }];
        
    }
    return _paintedDesView;
}

//- (NSString* )dictionaryToJson:(NSDictionary* )dic {
//    NSError* parseError = nil;
//    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
//    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//}
@end
